package com.example.demo.config;


import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.demo.pojo.LogTest;
import com.example.demo.pojo.UserInfoEnu;
import com.example.demo.service.Impl.UserServiceImpl;
import com.example.demo.utils.DfException;
import com.example.demo.utils.TokenUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
@Component
public class LoginHandlerInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        String token = request.getHeader("Authorization");
        response.setHeader("Access-Control-Allow-Origin", "*");
        if (token == null || token.equals("Bearer null")) {
            throw new DfException("请先登录");
        }
        DecodedJWT jwt = TokenUtils.verify(token);
        String name = jwt.getClaim("username").asString();
        String pass = jwt.getClaim("password").asString();
        BaseUserInfo.set("username",name);
        BaseUserInfo.set("password",pass);
        return true;
    }
    @Autowired
    private UserServiceImpl userService;
    public LogTest UserTokenLog(){
        String username = BaseUserInfo.get(UserInfoEnu.username.getCode());
        String password = BaseUserInfo.get(UserInfoEnu.password.getCode());
        LogTest logTest = userService.UserTokenLog(username, password);
        return logTest;
    }

}
